﻿using PosClient.ViewModel;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PosClient.View
{
    public partial class ChangePluPriceView : AntdUI.Window, IViewFor<ChangePluPriceViewModel>
    {
        object IViewFor.ViewModel
        {
            get => ViewModel;
            set => ViewModel = (ChangePluPriceViewModel)value;
        }
        public ChangePluPriceViewModel ViewModel { get; set; }

        public ChangePluPriceView(MainViewModel mainViewModel, bool isDiscount)
        {
            InitializeComponent();

            InitBinding(mainViewModel, isDiscount);

            InitEvent();
        }

        private void InitBinding(MainViewModel mainViewModel, bool isDiscount)
        {
            ViewModel = new ChangePluPriceViewModel(mainViewModel);
            this.WhenActivated(d =>
            {
                this.pageHeader1.SubText = mainViewModel.SelectPlu.PluName;

                ViewModel.IsDiscount = isDiscount;

                this.Events().Load
                    .Do(x => { ActiveControl = input_price; switch_type.Checked = isDiscount; })
                    .Subscribe()
                    .DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.PriceInput,
                    v => v.input_price.Text).DisposeWith(d);

                input_price.Events().KeyDown
                .Where(x => x.KeyData == Keys.Enter)
                .Do(e =>
                {
                    ViewModel.ChangePriceCommand.Execute().Subscribe(result =>
                    {
                        if (!result.Success)
                        {
                            var config = new AntdUI.Notification.Config(Globals.MainForm, "提醒", $"{result.Message}", AntdUI.TType.Error, AntdUI.TAlignFrom.Top);
                            AntdUI.Notification.open(config);
                        }
                    });
                })
                .Subscribe()
                .DisposeWith(d);

            });

            ViewModel.WhenAnyValue(x => x.IsDiscount).Subscribe(s =>
            {
                switch_type.Checked = s;
            });
        }

        private void InitEvent()
        {
            switch_type.CheckedChanged += (s, e) =>
            {
                ViewModel.IsDiscount = e.Value;
            };

            this.KeyDown += (s, e) =>
            {
                if (e.KeyData == Keys.Escape)
                {
                    this.Close();
                }
            };
        }
    }
}
